//
//  AJTTViewHistoryController.swift
//  JourneyThroughTime
//
//  Created by iOS-Czz on 2023/11/6.
//

import UIKit
import WebKit

class AJTTViewHistoryController: AJTTBaseViewController {
    lazy var webView: WKWebView = {
        let config = WKWebViewConfiguration.init()
        let preferences = WKPreferences()
        preferences.javaScriptEnabled = true
        config.preferences = preferences
        let webView = WKWebView.init(frame: CGRect.zero, configuration: config)
        webView.navigationDelegate = self
        return webView
    }()
    @IBOutlet var bgView: UIView!
    @IBOutlet var contentView: UIView!
    var htmlContent: String?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.contentView.addSubview(self.webView)

        self.loadHTML()
        // Do any additional setup after loading the view.
    }
    @IBAction func clickCloseAction(_ sender: Any) {
        self.dismiss(animated: true)
    }
    func loadHTML() {
        if let path = Bundle.main.path(forResource: "preview", ofType: "html") {
            let url = URL(fileURLWithPath: path)
            let request = URLRequest(url: url)
            print(url)
            webView.load(request)
        }
    }
    
    
    func setContent() {
        guard htmlContent != nil else {
            return
        }
        
        webView.evaluateJavaScript("insertContent('\(htmlContent!)')") { (val, err) in
            print("val: \(val ?? ""), err: \(String(describing: err))")
        }
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.bgView.addRoundCorners(topLeftRadius: 15, topRightRadius: 15, bottomLeftRadius: 0, bottomRightRadius: 0, borderWidth: 0, borderColor: .red)
        self.webView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
extension AJTTViewHistoryController: WKNavigationDelegate {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        // 禁止webview长按弹出menuControl
        self.webView.evaluateJavaScript(
            "document.documentElement.style.webkitTouchCallout='none';", completionHandler: nil)
        self.webView.evaluateJavaScript(
            "document.documentElement.style.webkitUserSelect='none';",
            completionHandler: nil)
        
        self.setContent()
    }
}
